"use strict";
const semver = require("semver");
const colors = require("colors");
const log = require("@pengsg-cli/log");
const LOWEST_NODE_VERSION = "13.0.0";

class Command {
  constructor(argv) {
    if (!argv) {
      throw new Error("argv不能为空");
    }
    if (!Array.isArray(argv)) {
      throw new Error("argv必须为数组");
    }
    if (argv.length === 0) {
      throw new Error("argv不能为空数组");
    }
    this._argv = argv;
    const runner = new Promise((resolve, reject) => {
      let chain = Promise.resolve();
      chain = chain.then(() => {
        this.checkNodeVersion();
      });
      chain = chain.then(() => {
        this.initArgs();
      });
      chain = chain.then(() => {
        this.init();
      });
      chain = chain.then(() => {
        this.exec();
      });
      chain.catch((err) => {
        log.error(err);
      });
    });
  }

  initArgs() {
    this._cmd = this._argv[this._argv.length - 1];
    this._argv = this._argv.slice(0, this._argv.length - 1);
  }

  checkNodeVersion() {
    const currentVersion = process.version;
    const minVersion = LOWEST_NODE_VERSION;
    if (!semver.gte(currentVersion, minVersion)) {
      throw new Error(
        colors.red(`pengsg-cli 需要安装不低于${minVersion}版本的Node`)
      );
    }
  }

  init() {
    throw new Error("必须实现Command的init方法");
  }

  exec() {
    throw new Error("必须实现Command的exec方法");
  }
}

module.exports = Command;
